<template>
	<view class="wrap">
		<view class="content">
			<view class="img">
				<u-image style="margin: 0 auto;" width="80%" mode="widthFix" height="200rpx"
					src="../../static/logo.png"></u-image>
			</view>
			<u-form :model="form" ref="uForm" class="form">
				<u-form-item label-width="100" prop="mobile" label="手机号" class="label">
					<u-input v-model="form.mobile" placeholder="请输入手机号" />
				</u-form-item>
				<u-form-item label-width="100" prop="captcha" label="验证码" class="label">
					<u-input v-model="form.captcha" placeholder="请输入验证码" />
					<u-verification-code :seconds="seconds" ref="uCode" @change="codeChange">
					</u-verification-code>
					<u-button size="mini" style="color: #2979ff;" plain @tap="getCode">{{tips}}</u-button>
				</u-form-item>
				<u-button style="margin: 20rpx 0;" type="primary" shape="circle" @click="submit">登录</u-button>
			</u-form>

			<view class="alternative">
				<u-checkbox-group>
					<u-checkbox v-model="checked" icon-size="24rpx" label-size="24rpx" shape="circle"
						@change="checkboxChange">
						点击登录则视您已详细阅读并同意
						<text style="font-size:24rpx; color:#2979ff ;" @click.stop="agreement">《小春云网站服务协议》</text>
					</u-checkbox>
				</u-checkbox-group>
			</view>
		</view>
		<view class="buttom">
			<view class="loginType">
				<view class="wechat item" v-if="isWinxin">
					<view class="three">使用第三方登录</view>
					<view class="icon">
						<u-icon size="70" name="weixin-fill" color="rgb(83,194,64)" @click="weixinLogin"></u-icon>
					</view>
				</view>
			</view>
		</view>
		<view>
			<u-toast ref="uToast" />
		</view>

    <view class="copyright">
      <view>Copyright@深圳市小春云科技有限公司 All Rights Reserved</view>
      <view><a href="https://beian.miit.gov.cn/">粤ICP备14056003号-2</a></view>
    </view>

		<u-modal v-model="aShow" confirm-text="确定" title="协议内容" @confirm="confirm">
			<view class="u-update-content">
				<scroll-view style="height: 1000rpx; " :show-scrollbar="true" :scroll-y="true" scroll-left
					scroll-with-animation="true">
					<u-parse style="padding: 20rpx;" :html="content"></u-parse>
				</scroll-view>
			</view>
		</u-modal>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				code: '',
				appId: "",
				aShow: false,
				content: "",
				seconds: 60,
				checked: false,
				tips: "",
				disabled: false,
				isWinxin: true,
				form: {
					mobile: "",
					captcha: "",
				},
				rules: {
					mobile: [{
						required: true,
						message: '请输入手机号',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}],
					captcha: [{
						required: true,
						message: '请输入验证码',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}]
				}
			}
		},
		computed: {},
		async onLoad(options) {
			if (options.isLogout) {
				window.location.href = 'http://' + window.location.host + "/index.html#/pages/login/login"
			}
			this.weixinBrowser()
			await this.geAppId()
			this.code = this.getUrlParam("code");
			if (this.code) {
				this.getUserInfoOfWechart(this.code)
			}
			this.code = ''
		},
		onHide() {
			this.code = ''
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		methods: {
			// 协议
			agreement() {
				this.aShow = true
				this.$u.api.getConfigInfo({
					key: "agreement"
				}).then(res => {
					this.content = res.data.content
				})
			},
			confirm() {
				this.aShow = false
			},
			codeChange(text) {
				this.tips = text
			},
			getCode() {
				//手机格式校验
				if (!this.$u.test.mobile(this.form.mobile)) {
					this.$refs.uToast.show({
						title: "请输入正确的手机号",
						type: 'error',
					});
					this.form.mobile = ""
					return false
				}
				if (this.$refs.uCode.canGetCode) {
					// 后端请求验证码
					uni.showLoading({
						title: '正在获取验证码'
					})
					let data = {
						event: 'mobilelogin',
						mobile: this.form.mobile
					}
					this.$u.api.send(data).then(res => {
						uni.hideLoading();
						if (res.code == 1) {
							// 这里此提示会被this.start()方法中的提示覆盖
							this.$u.toast('验证码已发送');
							// 通知验证码组件内部开始倒计时
							this.$refs.uCode.start();
						} else {
							this.$u.toast(res.msg)
						}
					})
				} else {
					this.$u.toast('倒计时结束后再发送');
				}
			},
			checkboxChange() {},
			submit() {
				//未点击同意服务
				this.$refs.uForm.validate(valid => {
					if (valid) {
						if (!this.checked) {
							this.$refs.uToast.show({
								title: "请点击同意《小春云网站服务协议》",
								type: "error"
							})
							return
						}
						this.mobeilLogin()
					}
				})

				// 提交请求数据

			},

			// 手机号登录
			async mobeilLogin() {
				this.$u.api.login(this.form).then(res => {
					if (res.code == 0) {
						this.$u.toast('验证码错误，请重新输入')
					} else if (res.code == 1) {
						this.$u.toast(res.msg)
						this.$u.vuex('vuex_token', res.data.userinfo.token);
						this.$u.vuex('vuex_user', res.data.userinfo)
						// uni.switchTab({
						// 	url: "/pages/list/list"
						// })
						this.$Router.push({
							name: "list"
						})
					}
				})
			},
			// 判断是否为微信浏览器
			weixinBrowser() {
				let ua = navigator.userAgent.toLowerCase();
				this.isWinxin = ua.indexOf('micromessenger') != -1;
			},
			// 判断公众号截取code
			getUrlParam(name) {
				let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
				console.log(reg)
				let r = window.location.search.substr(1).match(reg);
				if (r != null) {
					return unescape(r[2]);
				}
				return null;
			},

			// 获取appid
			geAppId() {
				this.$u.api.getConfigInfo({
					key: 'appid'
				}).then(res => {
					if (res.code == 1) {
						this.appId = res.data.value
					}
				})
			},

			// 微信登录
			weixinLogin() {
				this.code = ""
				if (!this.checked) {
					this.$refs.uToast.show({
						title: "请点击同意《小春云网站服务协议》",
						type: "error"
					})
					return
				}
				let code = this.getUrlParam("code"); //是否存在code
				let local = window.location.href;
				// if (code == null || code === "") {
				// 	//不存在就打开上面的地址进行授权
				// 	window.location.href =
				// 		`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.appId}&redirect_uri=${encodeURIComponent(local)}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect`;
				// } else {
				// 	this.getUserInfoOfWechart(code)
				// }
				if (window.location.href.indexOf("?code=") != -1) {
					var newUrl = location.href.split("?")[0];
					history.pushState('', '', newUrl); //参数可省略
				}
				window.location.href =
					`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.appId}&redirect_uri=${encodeURIComponent(local)}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect`;
			},
			// 获取微信个人信息
			getUserInfoOfWechart(code) {
				this.$u.api.loginByWeChatCode({
					code
				}).then(async res => {
					if (res.code == 0) {
						this.$u.toast(res.msg)
						console.log(res.data)
						let openid = res.data.openid
						let name = res.data.nickname
						let avatar = res.data.avatar
						// this.$u.route('/pages/addMobileNum/addMobileNum', {
						// 	openid,
						// 	name,
						// 	avatar
						// })
						this.$Router.push({
							path: "/addMobileNum",
							query: {
								openid,
								name,
								avatar
							}
						})

					} else if (res.code == 1) {
						this.$u.toast(res.msg)
						this.$u.vuex('vuex_token', res.data.token);
						// uni.switchTab({
						// 	url: "/pages/list/list"
						// })
						this.$Router.push({
							name: "list"
						})
					}


					// this.$u.vuex('vuex_token', res.data.token);
					// await this.getUserInfo()

					// uni.switchTab({
					// 	url: "/pages/list/list"
					// })


				})
			},
			// 获取用户信息
			// 得到个人信息,若手机号不存在，跳转到绑定手机号
			// getUserInfo() {
			// 	this.$u.api.getUserInfo().then(res => {
			// 		if (res.code === 1) {
			// 			if (!res.data.mobile) {
			// 				this.$u.route('/pages/addMobileNum/addMobileNum', {
			// 					name: res.data.name,
			// 					pic: encodeURIComponent(res.data.avatar)
			// 				})
			// 				return
			// 			} else {
			// 				uni.switchTab({
			// 					url: "/pages/list/list"
			// 				})
			// 			}
			// 		}
			// 	})
			// },
		}
	};
</script>

<style lang="scss" scoped>
  .copyright {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 450rpx;
    color: $u-content-color;
    font-size: 24rpx;
    a {
      color: rgb(41, 121, 255);
      text-decoration:none;
    }
  }

	.wrap {
		padding-top: 150rpx;
		font-size: 28rpx;

		.content {
			width: 600rpx;
			margin: 0 auto;

			input {
				text-align: left;
				margin-bottom: 10rpx;
				padding-bottom: 6rpx;
			}

			.label {
				font-weight: 600;
			}

			.getCaptcha {
				background-color: rgb(253, 243, 208);
				color: $u-tips-color;
				border: none;
				font-size: 30rpx;
				padding: 12rpx 0;

				&::after {
					border: none;
				}
			}

			.alternative {
				display: flex;
				justify-content: center;
				margin-top: 30rpx;
				margin-left: -20rpx;
			}
		}

		.buttom {
			.loginType {
				display: flex;
				padding: 250rpx 150rpx 0rpx 150rpx;
				justify-content: space-between;

				.three {
					font-size: 24rpx;
					margin-bottom: 40rpx;
				}

				.item {
					margin: 0 auto;
					display: flex;
					flex-direction: column;
					align-items: center;
					color: $u-content-color;
					font-size: 28rpx;
				}
			}
		}
	}
</style>
